<template>
  <div class="category-management">
    <el-card shadow="hover">
      <div class="card-header">
        <span>分类列表</span>
        <el-button type="primary" size="small" @click="openAddCategoryDialog"
          >添加分类</el-button
        >
      </div>
      <el-table :data="categoryList" border stripe highlight-current-row>
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="name" label="分类名称" align="center" />
        <el-table-column prop="type" label="分类级别" align="center">
          <template #default="scope">
            {{
              scope.row.type === 1
                ? "一级分类"
                : scope.row.type === 2
                ? "二级分类"
                : "三级分类"
            }}
          </template>
        </el-table-column>
        <el-table-column prop="parentId" label="父级分类" align="center">
          <template #default="scope">
            {{ getParentCategoryName(scope.row.parentId) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" min-width="160">
          <template #default="scope">
            <el-button type="text" size="small" @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button type="text" size="small" @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        :current-page="pageNum"
        :page-sizes="[5, 10, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount"
      />
    </el-card>

    <!-- 添加/编辑分类对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="400px">
      <el-form :model="formData" :rules="formRules" ref="formRef">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="formData.name" />
        </el-form-item>
        <el-form-item label="分类级别" prop="type">
          <el-select v-model="formData.type" @change="handleTypeChange">
            <el-option label="一级分类" value="1" />
            <el-option label="二级分类" value="2" />
            <el-option label="三级分类" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="父级分类" prop="parentId" v-if="showParentSelect">
          <el-select v-model="formData.parentId">
            <el-option
              v-for="item in parentOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      categoryList: [],
      pageNum: 1,
      pageSize: 5,
      totalCount: 0,
      dialogVisible: false,
      dialogTitle: "添加分类",
      formData: {
        id: null,
        name: "",
        type: 1,
        parentId: null,
      },
      formRules: {
        name: [{ required: true, message: "请输入分类名称", trigger: "blur" }],
        type: [
          { required: true, message: "请选择分类级别", trigger: "change" },
        ],
      },
      parentOptions: [],
      showParentSelect: false,
    };
  },
  mounted() {
    this.fetchCategoryList();
  },
  methods: {
    // 获取分类列表
    async fetchCategoryList() {
      try {
        const response = await this.$axios.get(
          "/easybuy/category/categoryList",
          {
            params: {
              pageNum: this.pageNum,
              pageSize: this.pageSize,
            },
          }
        );

        console.log("分类列表响应:", response.data);

        if (response.data.code === "200") {
          this.categoryList = response.data.pageInfo.list || [];
          this.totalCount = response.data.pageInfo.total || 0;

          // 缓存所有分类用于父级选择
          this.parentOptions = this.categoryList.filter(
            (item) => item.type < 3
          );
        } else {
          this.$message.error(response.data.message || "获取分类列表失败");
        }
      } catch (error) {
        console.error("获取分类列表错误:", error);
        this.$message.error("网络错误，请稍后重试");
      }
    },

    // 处理分页
    handleCurrentChange(newPage) {
      this.pageNum = newPage;
      this.fetchCategoryList();
    },

    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.fetchCategoryList();
    },

    // 获取父级分类名称
    getParentCategoryName(parentId) {
      if (parentId === 0) return "顶级分类";

      const parent = this.categoryList.find((item) => item.id === parentId);
      return parent ? parent.name : "未知分类";
    },

    // 打开添加分类对话框
    openAddCategoryDialog() {
      this.dialogTitle = "添加分类";
      this.formData = {
        id: null,
        name: "",
        type: 1,
        parentId: null,
      };
      this.showParentSelect = false;
      this.dialogVisible = true;
    },

    // 打开编辑分类对话框
    handleEdit(row) {
      this.dialogTitle = "编辑分类";
      this.formData = { ...row };
      this.showParentSelect = row.type > 1;
      this.dialogVisible = true;
    },

    // 处理分类级别变更
    handleTypeChange() {
      this.showParentSelect = this.formData.type > 1;

      // 如果切换为一级分类，重置父级ID
      if (this.formData.type === 1) {
        this.formData.parentId = null;
      }
    },

    // 提交表单
    async submitForm() {
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          try {
            let response;

            if (this.formData.id) {
              // 更新分类
              response = await this.$axios.post(
                "/easybuy/category/updateCategory",
                {
                  params: this.formData,
                }
              );
            } else {
              // 添加分类
              response = await this.$axios.post(
                "/easybuy/category/addCategory",
                {
                  params: this.formData,
                }
              );
            }

            if (response.data.code === "200") {
              this.$message.success(this.formData.id ? "更新成功" : "添加成功");
              this.dialogVisible = false;
              this.fetchCategoryList();
            } else {
              this.$message.error(
                response.data.message ||
                  (this.formData.id ? "更新失败" : "添加失败")
              );
            }
          } catch (error) {
            console.error(
              this.formData.id ? "更新分类错误" : "添加分类错误",
              error
            );
            this.$message.error("网络错误，请稍后重试");
          }
        } else {
          return false;
        }
      });
    },

    // 删除分类
    async handleDelete(row) {
      this.$confirm("确定要删除该分类吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            const response = await this.$axios.post(
              "/easybuy/category/deleteCategory",
              {
                params: { id: row.id },
              }
            );

            if (response.data.code === "200") {
              this.$message.success("删除成功");
              this.fetchCategoryList();
            } else {
              this.$message.error(response.data.message || "删除失败");
            }
          } catch (error) {
            console.error("删除分类错误:", error);
            this.$message.error("网络错误，请稍后重试");
          }
        })
        .catch(() => {
          // 取消操作
        });
    },
  },
};
</script>

<style scoped>
.category-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>